import express from "express";

import { getRagChain } from "./index";

const app = express();
const port = 3889;
app.use(express.json());

console.log("🚀 正在初始化服务器...");

let ragChain: any = null;

// 预先初始化 ragChain
(async () => {
  try {
    console.log("⏳ 正在加载 RAG Chain...");
    ragChain = await getRagChain();
    console.log("✅ RAG Chain 加载完成");
  } catch (error) {
    console.error("❌ RAG Chain 加载失败:", error);
  }
})();

app.post("/rag", async (req, res) => {
  try {
    if (!ragChain) {
      return res.status(503).json({ error: "RAG Chain 尚未初始化完成，请稍后重试" });
    }

    const body = req.body;
    if (!body.question) {
      return res.status(400).json({ error: "缺少 question 参数" });
    }
    if (!body.session_id) {
      return res.status(400).json({ error: "缺少 session_id 参数" });
    }

    console.log(`📝 收到问题: ${body.question}, 会话ID: ${body.session_id}`);

    const result = await ragChain.stream(
      {
        question: body.question,
      },
      { configurable: { sessionId: body.session_id } }
    );

    res.set("Content-Type", "text/plain");
    for await (const chunk of result) {
      res.write(chunk);
    }
    res.end();
    console.log("✅ 响应完成");
  } catch (error) {
    console.error("❌ 处理请求时出错:", error);
    res.status(500).json({ error: "服务器内部错误" });
  }
});

app.listen(port, () => {
  console.log(`🎉 服务器已启动，监听端口: ${port}`);
  console.log(`📡 POST http://localhost:${port}/rag`);
});
